<script lang="ts" setup>
import type { RowType } from '../../types';

import { useVbenModal ,z} from '@vben/common-ui';
import { watch ,ref} from 'vue';
import { message ,SelectOption,Select,Input} from 'ant-design-vue';
import { $t } from '@vben/locales';
import { useVbenForm } from '#/adapter/form';
import { postSlideItems, putSlideItems } from '#/api/admin/slideItems';
import {  getPage } from '#/api/admin/themefile';
import { getPage as getNews } from '#/api/portal/news';
import { getArticle } from '#/api/portal/article';
const [Form, formApi] = useVbenForm({
  handleSubmit: onSubmit,
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['slide_id'],
      },
      fieldName: 'slide_id',
      label: 'slide_id',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: $t("page.common.Please Enter"),
      },
      fieldName: 'title',
      label: $t("page.common.Title"),
      rules: z.string().max(50,$t('admin.maxChars', { length: 50 }))
      
    },
    {
      component: 'Select',
      fieldName: 'url',
      label: $t('admin.redirectUrl'),
      slots:{default:'url'}
    },

    {
        component: 'Select',
        defaultValue: '',
        componentProps: {
            class: 'w-full',
            filterOption: true,
            allowClear: true,
            showSearch: true,
             options: [
                 {
                  label:'',
                  value:'',
                },
                {
                  label:'All Models',
                  value:'#modelall',
                }
                ,
                {
                    label: 'Mid-Size Models',
                    value: '?type=mid#modelall',
                },
                {
                    label: 'Full-Size Models',
                    value:  '?type=full#modelall',
                },
                {
                    label: 'Bottom',
                    value:  '#Bottom',
                },
             ]
        },
        fieldName: 'target_position',
        label: $t('admin.redirectPosition'),
        
    },
    {
      component: 'Upload',
      defaultValue: '',
      componentProps: {
        tips:'size:3840x1920'
      },
      fieldName: 'image',
      label: $t("page.common.Thumbnail"),
      rules: 'required',
    },
    {
      component: 'Upload',
      defaultValue: '',
      componentProps: {
        tips:'size:1080×1920'
      },
      fieldName: 'image_mobile',
      label: $t('admin.mobileThumbnail'),
    },
    {
      component: 'Select',
      defaultValue: '_blank',
      componentProps: {
        placeholder: $t("page.common.Please Enter"),
        options: [
          {
            label: $t('admin.newWindow')+'(_blank)',
            value: '_blank',
          },
          {
            label: $t('admin.currentWindow')+'(_self)',
            value: '_self',
          },
          // {
          //   label: '父窗口(_parent)',
          //   value: '_parent',
          // },
          // {
          //   label: '主窗口(_top)',
          //   value: '_top',
          // },
        ],
      },
      rules: 'required',
      fieldName: 'target',
      label: $t('admin.Open Method'),
    },
    {
      component: 'Select',
      defaultValue: 'right',
      componentProps: {
        class:'w-full',
        placeholder: $t("page.common.Please Enter"),
        options: [
          {
            label: 'right',
            value: 'right',
          },
          {
            label: 'left',
            value: 'left',
          },
          {
            label: 'right bottom',
            value: 'right_bottom',
          }
        ],
      },
      rules: 'required',
      fieldName: 'text_direction',
      label: $t('admin.copyPosition'),
    },
    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t("page.common.Please Enter"),
      },
      fieldName: 'description',
      label: $t("page.common.Description"),
    },
    {
      component: 'Textarea',
      componentProps: {
        placeholder: $t("page.common.Please Enter"),
      },
      fieldName: 'content',
      label: $t('admin.slideContent'),
    },
  ],
  showDefaultActions: false,
});

const [Modal, formModalApi] = useVbenModal({
  fullscreenButton: false,
  onCancel() {
    formModalApi.close();
  },
  onConfirm: async () => {
    await formApi.validateAndSubmitForm();
    formModalApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const values: RowType = formModalApi.getData();
      if (values) {
        formApi.setValues(values);
        linkType.value = values.target_type
       
        handleSearch(values.target_value_label)
        if(values.target_value){
    
              init_url.value = linkType.value!=='自定义页面'?parseInt(values.target_value):values.target_value;
        }else{
          init_url.value='';
        }
        
      }
    }
  },
});
const linkType = ref('');
const linkOptions = ref<SelectOption[]>([]);
const init_url = ref('');
async function onSubmit(values: any) {

    function showMsg(msg: string) {
      message.success(msg);
      formModalApi.setData({ isUpdata: true });
    }

    values.target_type=linkType.value??'';
    values.target_value=init_url.value??'';



    if(values.target_type=='' && values.target_value==''){
      values.url=values.target_position;
    }
   

    if (values.id) {

      const { msg } = await putSlideItems(values.id, values);
      showMsg(msg);
    } else {
      const { msg } = await postSlideItems(values);
      showMsg(msg);
    }
}

function handleSelectChange(){
 
  handleSearch('');
  init_url.value='';
}

async function handleSearch(value: string){

  if (linkType.value === '系统页面') {
          const { data } = await  getPage({
              page: 1,
              limit: 20,
              keyword:value
          });

          linkOptions.value = data.list.map(item => ({
              label: item.name,  
              value: item.id 
          }));
          return;
  }else if(linkType.value == '新闻详情'){
    const { data } = await getNews({
          page: 1,
          limit: 20,
          keyword:value
    });

    linkOptions.value = data.list.map(item => ({
        label: item.news_title,  // name 作为 label
        value: item.id     // id 作为 value
    }));


    return;
  }else if(linkType.value == '广宣品详情'){
        const { data } = await getArticle({
          page: 1,
          limit: 20,
          code:'article',
          keyword:value
        });

     linkOptions.value = data.list.map(item => ({
        label: item.post_title,  // name 作为 label
        value: item.id     // id 作为 value
    }));   
  }else if(linkType.value == '配件详情'){
     const { data } = await getArticle({
          page: 1,
          limit: 20,
          code:'parts',
          keyword:value
        });

     linkOptions.value = data.list.map(item => ({
        label: item.post_title,  // name 作为 label
        value: item.id     // id 作为 value
    }));   
  }
}


</script>
<template>
  <Modal class="w-3/5">
    <Form>
      
      <template #url="{ row }">
          <template class="flex" style="gap:1rem"> 
               <Select v-model:value="linkType" :placeholder="$t('page.common.Please Select')" style="width: 150px" @update:value="handleSelectChange" :allowClear="true"  >
                  <SelectOption value="系统页面">{{$t('admin.systemPage')}}</SelectOption>
                   <SelectOption value="新闻详情">{{$t('admin.newsDetail')}}</SelectOption>
                   <SelectOption value="广宣品详情">{{$t('admin.promotionDetail')}}</SelectOption>
                   <SelectOption value="配件详情">{{$t('admin.partsDetail')}}</SelectOption>
                   <SelectOption value="自定义页面">{{$t('admin.customPage')}}</SelectOption>
               </Select>


                  <Select
                      v-if="linkType !== '自定义页面'"
                      :options="linkOptions"
                      v-model:value="init_url"
                      :showSearch="true"
                      :filterOption="false"
                      :allowClear="true"  
                      :placeholder="$t('page.common.Please Select')"
                      style="width: 240px"
                      @search="handleSearch"
                      @focus="handleSearch('')"
                      @clear="handleSearch('')"
                    />

                    <Input
                      v-if="linkType === '自定义页面'"
                      v-model:value="init_url"
                      :placeholder="$t('page.common.Please Enter')"
                      style="width: 240px"
                    />

          </template>
      </template>

      
    </Form>
  </Modal>
</template>

<style lang="scss" scoped></style>
